[Python] Tips for making a fraction calculator code more optimized (faster and using less memory)
Posted
by Logic Named Joe
on Stack Overflow
See other posts from Stack Overflow
or by Logic Named Joe
Published on 2010-06-06T20:30:49Z
Indexed on
2010/06/06
20:42 UTC
Read the original article
Hit count: 199
Hello Everyone,
Basicly, what I need for the program to do is to act a as simple fraction calculator (for addition, subtraction, multiplication and division) for the a single line of input, for example:
-input: 1/7 + 3/5
-output: 26/35
My initial code:
import sys
def euclid(numA, numB):
while numB != 0:
numRem = numA % numB
numA = numB
numB = numRem
return numA
for wejscie in sys.stdin:
wyjscie = wejscie.split(' ')
a, b = [int(x) for x in wyjscie[0].split("/")]
c, d = [int(x) for x in wyjscie[2].split("/")]
if wyjscie[1] == '+':
licz = a * d + b * c
mian= b * d
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
elif wyjscie[1] == '-':
licz= a * d - b * c
mian= b * d
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
elif wyjscie[1] == '*':
licz= a * c
mian= b * d
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
else:
licz= a * d
mian= b * c
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
Which I reduced to:
import sys
def euclid(numA, numB):
while numB != 0:
numRem = numA % numB
numA = numB
numB = numRem
return numA
for wejscie in sys.stdin:
wyjscie = wejscie.split(' ')
a, b = [int(x) for x in wyjscie[0].split("/")]
c, d = [int(x) for x in wyjscie[2].split("/")]
if wyjscie[1] == '+':
print("/".join([str((a * d + b * c)/euclid(a * d + b * c, b * d)),str((b * d)/euclid(a * d + b * c, b * d))]))
elif wyjscie[1] == '-':
print("/".join([str((a * d - b * c)/euclid(a * d - b * c, b * d)),str((b * d)/euclid(a * d - b * c, b * d))]))
elif wyjscie[1] == '*':
print("/".join([str((a * c)/euclid(a * c, b * d)),str((b * d)/euclid(a * c, b * d))]))
else:
print("/".join([str((a * d)/euclid(a * d, b * c)),str((b * c)/euclid(a * d, b * c))]))
Any advice on how to improve this futher is welcome.
Edit: one more thing that I forgot to mention - the code can not make use of any libraries apart from sys.
© Stack Overflow or respective owner